<?php

use Illuminate\Database\Capsule\Manager as DB;

#[定时发收益控制器]
class ScriptController extends CoreController
{
    public function init()
    {
        if (!$this->isCli()) {
            throw new Exception("Go to cli please!", '303');
        }
        parent::init();
    }

    #[发放收益员]
    public function runAction()
    {
        $cashBackCnf = \configModel::query()->where('type', 19)->pluck('value', 'key')->toArray();
        $ratio = $cashBackCnf['cashback_pre_day_ratio'];
        $days  = $cashBackCnf['can_tomoney_days'];
        $amount= 0.00;
        orderModel::query()
            ->join('order_item', 'order.id', '=', 'order_item.order_id')
            ->where('order.paytime', '<', time()-86400*$days)
            ->where('order_item.cashback', '>', 0)
            ->where('order.status', '>', 0)
            ->select('order_item.id', 'order_item.member_id', 'order_item.cashback', 'order_item.pay_price')
            ->orderBy('order.paytime', 'asc')
            ->chunk(100, function ($orderItems) use($ratio, &$amount) {
                foreach ($orderItems as $item) {
                    if(membermoneylogModel::query()->where('event', 'cashback')->where('event_id', $item->id)->whereDate('created_at', date('Y-m-d'))->exists()){continue;}

                    $money = round($item->pay_price  * $ratio * 0.01, 2);
                    $money = $money > $item->cashback ? $item->cashback : $money;
                    $amount+= $money;

                    DB::transaction(function() use($money, $item){
                        orderitemModel::query()->where('id', $item->id)->decrement('cashback', $money);
                        \memberModel::quanyi(-1 * $money, $item->member_id , 'cashback', $item->id, '每日返现补贴从权益值扣除相应金额');
                        \memberModel::money($money, $item->member_id , 'cashback', $item->id, '每日返现补贴转入余额');
                    });
                }
            });

        echo 'Done, 共发放返现补贴：', $amount, '元', PHP_EOL;
    }

}
